package org.codehaus.activemq.filter;

import javax.jms.JMSException;
import javax.jms.Message;

public class ConstantExpression
  implements Expression
{
  public static final BooleanConstantExpression NULL = new BooleanConstantExpression(null);
  public static final BooleanConstantExpression TRUE = new BooleanConstantExpression(Boolean.TRUE);
  public static final BooleanConstantExpression FALSE = new BooleanConstantExpression(Boolean.FALSE);
  private Object value;

  public static ConstantExpression createInteger(String text)
  {
    Number value = new Long(text);
    long l = value.longValue();
    if ((-2147483648L <= l) && (l <= 2147483647L)) {
      value = new Integer(value.intValue());
    }
    return new ConstantExpression(value);
  }

  public static ConstantExpression createFloat(String text) {
    Number value = new Double(text);
    return new ConstantExpression(value);
  }

  public ConstantExpression(Object value) {
    this.value = value;
  }

  public Object evaluate(Message message) throws JMSException {
    return this.value;
  }

  public String toString()
  {
    if (this.value == null) {
      return "NULL";
    }
    if ((this.value instanceof Boolean)) {
      return ((Boolean)this.value).booleanValue() ? "TRUE" : "FALSE";
    }
    if ((this.value instanceof String)) {
      return encodeString((String)this.value);
    }
    return this.value.toString();
  }

  public int hashCode()
  {
    return toString().hashCode();
  }

  public boolean equals(Object o)
  {
    if ((o == null) || (!getClass().equals(o.getClass()))) {
      return false;
    }
    return toString().equals(o.toString());
  }

  private String encodeString(String s)
  {
    StringBuffer b = new StringBuffer();
    b.append('\'');
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      if (c == '\'') {
        b.append(c);
      }
      b.append(c);
    }
    b.append('\'');
    return b.toString();
  }

  static class BooleanConstantExpression extends ConstantExpression
    implements BooleanExpression
  {
    public BooleanConstantExpression(Object value)
    {
      super(value);
    }
  }
}